import os
from typing import Annotated

import httpx
from dotenv import find_dotenv, load_dotenv
from langchain_core.tools import tool

_ = load_dotenv(find_dotenv())


@tool
def route_planning(
    origin: Annotated[str, "出发点的经纬度,小数点后不超过6位,以,号分割,经度在前纬度在后"],
    destination: Annotated[str, "出发地的经纬度,小数点后不超过6位,以,号分割,经度在前纬度在后"],
    origin_city_code: Annotated[str, "出发点的城市编码"],
    dest_city_code: Annotated[str, "目的地城市编码.非必填,跨城市必填."] = "",
):
    """路线规划工具。规划综合各类公共交通方式（火车、公交、地铁）的交通方案，返回从出发点到目的地的步行距离、
    出租车费用以及公共交通方案列表。返回结果中，距离的单位都是米，时间的单位都是秒，费用的单位都是元。
    如果返回的公共交通方案列表为空，说明两个地点之间没有可用的公共交通方式。"""

    url = r"https://restapi.amap.com/v3/direction/transit/integrated"
    amap_key = os.getenv("AMAP_API_KEY")

    params = {
        "origin": origin,
        "destination": destination,
        "city": origin_city_code,
        "cityd": dest_city_code,
        "key": amap_key,
    }

    response = httpx.get(url, params=params).json()

    if response["status"] == "0":
        raise ValueError(
            f"获取从{origin}到{destination}的交通方案失败。请检查出发点、目的地和城市编码是否正确。错误信息: {response['info']}"
        )

    routes = {
        "origin": response["route"]["origin"],
        "destination": response["route"]["destination"],
        "walking_distance": response["route"]["distance"],
        "taxi_cost": response["route"]["taxi_cost"]
        if response["route"]["taxi_cost"] != "0"
        else "not available",
        "public_transport_options_list": [],
    }

    for item in response["route"]["transits"]:
        routes["public_transport_options_list"].append(
            {"cost": item["cost"], "duration": item["duration"], "walking_distance": item["walking_distance"]}
        )

    return routes


if __name__ == "__main__":
    print(
        route_planning.invoke(
            {
                "origin": "113.129362,29.371356",
                "destination": "112.960976,28.184095",
                "origin_city_code": "0730",
                "dest_city_code": "0730",
            }
        )
    )
